package com.ykdl.member.kid.beans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ykdl.member.kid.models.CatalogArticleItem;
import com.ykdl.member.kid.models.CatalogBean;
import com.ykdl.member.kid.models.CatalogItemBean;
import com.ykdl.member.kid.models.CatalogTopicItem;

import net.wxxr.http.interfaces.IJsonParser;

public class TopicSheetList implements Serializable, IJsonParser {
	private static final long serialVersionUID = -5661945395665627722L;

	private CatalogBean catalog;

	public CatalogBean getCatalog() {
		return catalog;
	}

	public void setCatalog(CatalogBean catalog) {
		this.catalog = catalog;
	}

	@Override
	public IJsonParser parse(String json) throws Exception {
		Gson gson = null;
		final TopicSheetList bean = new TopicSheetList();
		
		if (null != json) {
			GsonBuilder b = new GsonBuilder();
			gson = b.create();
			final JSONObject object = new JSONObject(json);
			//取得catalog节点的数据字典
			final String catalog_json = object.getString("catalog");
			final  CatalogBean catalogben = gson.fromJson(catalog_json, CatalogBean.class);
			//catalog节点数据为空，返回
			if ("null".equals(catalog_json) || catalog_json.equals("{}"))
				return bean;
			
			JSONObject jo = new JSONObject(catalog_json);
			//获得catalog类型，1-话题 2-文章 3-问题
			int catalog_type = jo.getInt("catalog_type");
			String catalog_tag = jo.getString("tag");
			//获得catalog数据字典中key为items的数据字典
			final String catalog_items = jo.getString("items");
			//items数据字典为空，返回
			if (catalog_items == null || catalog_items.equals("[]")
					|| "null".equals(catalog_items)){
				bean.setCatalog(catalogben);
				return bean;
			}
			final List<CatalogItemBean> items = new ArrayList<CatalogItemBean>();
			final JSONArray items_json_array = new JSONArray(catalog_items);
			JSONObject item_object = null;
			CatalogItemBean item = null;
			//根据catalog_type不同解析不同的CatalogItemBean，并添加到集合中
			for (int i = 0; i < items_json_array.length(); i++) {
				item_object = items_json_array.getJSONObject(i);
				//获得items数据字典中key为item的数据字典
				final String json_item = item_object.getString("item");
				//如果item数据字典为空，返回
				//if (null == json_item || "null".equals(json_item)|| "{}".equals(json_item))
				//	continue;
				
				if (catalog_type == 1 && catalog_tag.equals("groups")) { // 普通群组专题
					item = gson.fromJson(items_json_array.getString(i), CatalogTopicItem.class);
				} else if (jo.getInt("catalog_type") == 2 && catalog_tag.equals("clinic")) {//医生专题
					item = gson.fromJson(items_json_array.getString(i),CatalogTopicItem.class);
				}
					
				items.add(item);
			}
			
			CatalogBean catalog = gson.fromJson(catalog_json, CatalogBean.class);
			if (items != null) {
				catalog.setCatalogItems(items);
			}
			
			bean.setCatalog(catalog);
		}
		return bean;
	}

}
